package com.ecoolex.hotel.saas.job.scheduler;

import java.util.Calendar;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import com.ecoolex.framework.common.util.Check;
import com.ecoolex.framework.scheduler.Job;
import com.ecoolex.framework.scheduler.JobComponent;
import com.ecoolex.hotel.saas.core.manager.PresaleCouponOrderDetailManager;
import com.ecoolex.hotel.saas.core.manager.PresaleCouponOrderManager;
import com.ecoolex.hotel.saas.core.manager.StoreOrderConfigManager;
import com.ecoolex.hotel.saas.entity.PresaleCouponOrder;
import com.ecoolex.hotel.saas.entity.PresaleCouponOrderDetail;
import com.ecoolex.hotel.saas.entity.StoreOrderConfig;

@JobComponent
public class PresaleCouponOrderCheckJob {

	private static final Logger log = LoggerFactory.getLogger(PresaleCouponOrderCheckJob.class);
	
	@Autowired
	private PresaleCouponOrderManager orderManager;
	
	@Autowired
	private StoreOrderConfigManager storeOrderConfigManager;
	
	@Autowired
	private PresaleCouponOrderDetailManager presaleCouponOrderDetailManager;
	
	//待支付订单到期自动取消
	@Job(name = "hotel.saas.PresaleCouponOrderCheckJob.autoCloseOrder", describe = "自动取消未支付的预售券订单")
	public void autoCancel() {
		Calendar calendar = Calendar.getInstance();
		List<PresaleCouponOrder> list = orderManager.queryUnpaid(10);
		list.forEach(order -> {
			StoreOrderConfig config = storeOrderConfigManager.getStoreOrderConfig(order.getStoreId());
			Integer cancelTime = config.getAutoCancelTime();
			calendar.add(Calendar.MINUTE, -cancelTime);
			if(Check.isLessThanEqual(order.getCreateTime(), calendar.getTime())) {
				orderManager.autoCancel(order, PresaleCouponOrderCheckJob.class.getSimpleName());
			}
		});
	}
	
	//已发放到订单明细中的预售券过期检查
	@Job(name = "hotel.saas.PresaleCouponOrderExpireCheckJob.checkExpire", describe = "检查已发放的预售券过期状态")
	public void checkPresaleCouponExpire() {
		Calendar calendar = Calendar.getInstance();
		List<PresaleCouponOrderDetail> list = presaleCouponOrderDetailManager.queryExpire(calendar.getTime(), 10);
		list.forEach(d -> {
			presaleCouponOrderDetailManager.expire(d, PresaleCouponOrderCheckJob.class.getSimpleName());
		});
	}
}
